﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FRL.DebtChased.Silverlight.Library.RichContentService;
using System.ComponentModel;
using FRL.DebtChased.Silverlight.Library;


namespace FRL.DebtChased.ChaseWorkspace
{
    public partial class DebtDetailsCtrl : UserControl, INotifyPropertyChanged
    {
        /////////////////////////////////////////////////////////////
        // Interface & Constructor

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public DebtDetailsCtrl()
        {
            InitializeComponent();
            //this.Totals = new List<DebtSummaryObject>();
            //this.Totals.Add(new DebtSummaryObject());
            this.Totals = new DebtSummaryObject();
            this.DatagridTotals = new ObservableCollection<DebtSummaryObject>();
            this.DatagridTotals.Add(Totals);
            this.LayoutRoot.DataContext = this;
            TabSelected = DebtAnalysisTabSelection.Breakdown;
            debtAnalysisTabCtrl.SelectionChanged += new SelectionChangedEventHandler(debtAnalysisTabCtrl_SelectionChanged);
            //this.Loaded += new RoutedEventHandler(DebtDetailsCtrl_Loaded);
        }

        /*
        void DebtDetailsCtrl_Loaded(object sender, RoutedEventArgs e)
        {
            SetData1();
        }
        /**/

        /////////////////////////////////////////////////////////////
        // "Properties"

        public AccountTransport _account;
        public AccountTransport Account
        {
            get { return _account; }
            set
            {
                if (value != _account)
                {
                    this._account = value;
                    RaisePropertyChanged("Account");
                    this.Invoices = _account.AccountInvoices;
                }
            }
        }

        private ObservableCollection<AccountInvoiceTransport> _invoices;
        public ObservableCollection<AccountInvoiceTransport> Invoices
        {
            get { return _invoices; }
            set
            {
                if (value != _invoices)
                {
                    _invoices = value;

                    debtDetailDataGrid.ItemsSource = Invoices;
                    debtDetailTotalGrid.ItemsSource = DatagridTotals;
                    RaisePropertyChanged("Invoices");

                    UpdateTotals();
                    AllignTotals();
                }
            }
        }

        /////////////////////////////////////////////////////////////
        // Workings

        private void Invoice_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            UpdateTotals();
        }

        //public List<DebtSummaryObject> Totals;
        public DebtSummaryObject Totals;
        public ObservableCollection<DebtSummaryObject> DatagridTotals;

        private void UpdateTotals()
        {
            Money2 total = new Money2(0);
            foreach (AccountInvoiceTransport invoice in Invoices)
            {
                total += invoice.Amount;
            }
            Totals.Paid = total;
        }


        #region // Column constants
        private const int ColType = 0;
        private const int ColReference = 1;
        private const int ColStatus = 2;
        private const int ColSubStatus = 3;
        private const int ColDate = 4;
        private const int ColDueDate = 5;
        private const int ColDebtPassed = 6;
        private const int ColLpcda = 7;
        private const int ColPaidPreviously = 8;
        private const int ColBalance = 9;
        private const int ColExpected = 10;
        private const int ColPaid = 11;
        private const int ColNewBalance = 12;
        private const int ColLight = 13;
        private const int ColButtons = 14;
        #endregion

        /////////////////////////////////////////////////////////////
        // Event Handlers

        private DebtAnalysisTabSelection _tabSelection;
        public DebtAnalysisTabSelection TabSelected
        {
            get { return _tabSelection; }
            set
            {
                //_tabSelection = (DebtAnalysisTabSelection)debtAnalysisTabCtrl.SelectedIndex;
                _tabSelection = value;
                switch (value)
                {
                    case DebtAnalysisTabSelection.Breakdown:
                        ReasonTextBlock.Visibility = Visibility.Collapsed;
                        debtAnalysisGrid.Visibility = Visibility.Visible;

                        debtDetailDataGrid.Columns[ColStatus].Visibility = Visibility.Visible;
                        debtDetailDataGrid.Columns[ColSubStatus].Visibility = Visibility.Collapsed;

                        debtDetailDataGrid.Columns[ColPaidPreviously].Header = "Paid";

                        debtDetailDataGrid.Columns[ColExpected].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColPaid].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColNewBalance].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColLight].Visibility = Visibility.Visible;
                        debtDetailDataGrid.Columns[ColButtons].Visibility = Visibility.Visible;
                        receiptDetailsGrid.Visibility = Visibility.Collapsed;
                        break;
                    case DebtAnalysisTabSelection.Expected:
                        ReasonTextBlock.Visibility = Visibility.Collapsed;
                        debtAnalysisGrid.Visibility = Visibility.Visible;

                        debtDetailDataGrid.Columns[ColStatus].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColSubStatus].Visibility = Visibility.Visible;

                        debtDetailDataGrid.Columns[ColPaidPreviously].Header = "Paid Previously";

                        debtDetailDataGrid.Columns[ColExpected].Visibility = Visibility.Visible;
                        debtDetailDataGrid.Columns[ColPaid].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColNewBalance].Visibility = Visibility.Visible;
                        debtDetailDataGrid.Columns[ColLight].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColButtons].Visibility = Visibility.Collapsed;
                        PaidToLabel.Text = "Paying\nTo";
                        receiptDetailsGrid.Visibility = Visibility.Visible;
                        break;
                    case DebtAnalysisTabSelection.Invoicing:
                        ReasonTextBlock.Visibility = Visibility.Collapsed;
                        debtAnalysisGrid.Visibility = Visibility.Visible;

                        debtDetailDataGrid.Columns[ColStatus].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColSubStatus].Visibility = Visibility.Visible;

                        debtDetailDataGrid.Columns[ColPaidPreviously].Header = "Paid Previously";

                        debtDetailDataGrid.Columns[ColExpected].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColPaid].Visibility = Visibility.Visible;
                        debtDetailDataGrid.Columns[ColNewBalance].Visibility = Visibility.Visible;
                        debtDetailDataGrid.Columns[ColLight].Visibility = Visibility.Collapsed;
                        debtDetailDataGrid.Columns[ColButtons].Visibility = Visibility.Collapsed;
                        PaidToLabel.Text = "Paid\nTo";
                        receiptDetailsGrid.Visibility = Visibility.Visible;
                        break;
                    case DebtAnalysisTabSelection.Reason:
                        debtAnalysisGrid.Visibility = Visibility.Collapsed;
                        ReasonTextBlock.Visibility = Visibility.Visible;
                        break;
                }
            }
        }

        private void debtAnalysisTabCtrl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabSelected = (DebtAnalysisTabSelection)debtAnalysisTabCtrl.SelectedIndex;
        }
        private void debtDetailDataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            //if ((string)e.Column.Header == "Status")
            //{
            //    ComboBox cbo = (ComboBox)e.EditingElement;
            //    cbo.SetBinding(ComboBox.SelectedItemProperty, new System.Windows.Data.Binding("Status")
            //    {
            //        Source = e.Row.DataContext,
            //        Mode = System.Windows.Data.BindingMode.TwoWay
            //    });
            //    cbo.SetBinding(ComboBox.DisplayMemberPathProperty, new System.Windows.Data.Binding("Value"));
            //    cbo.SetBinding(ComboBox.SelectedValuePathProperty, new System.Windows.Data.Binding("Key"));
            //    cbo.SetBinding(ComboBox.ItemsSourceProperty, new System.Windows.Data.Binding()
            //    {
            //        Source = DataCache.InvoiceStatuses

            //    });
            //}
        }

        private void debtDetailDataGrid_LayoutUpdated(object sender, EventArgs e)
        {
            AllignTotals();
        }

        private void debtDetailDataGrid_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {

        }


        /////////////////////////////////////////////////////////////
        // Helper Methods

        public void AllignTotals()
        {
            //for (int i = 0; i < 10; i++)
            //{
            //    if (debtDetailDataGrid.Columns[i].Visibility == Visibility.Collapsed)
            //        debtDetailTotalsGrid.ColumnDefinitions[i].Width = new GridLength(0);
            //    else
            //        debtDetailTotalsGrid.ColumnDefinitions[i].Width = new GridLength(debtDetailDataGrid.Columns[i].ActualWidth);
            //}
            AllignDataGridColumns(debtDetailDataGrid, debtDetailTotalGrid);
        }

        public static void AllignDataGridColumns(DataGrid master, DataGrid slave)
        {
            if (master != null && slave != null)
            {
                int cols = Math.Min(master.Columns.Count, slave.Columns.Count);
                int?[] display = new int?[cols];

                for (int i = 0; i < cols; i++)
                {
                    //slave.ColumnDefinitions[i].Width = new GridLength((master.Columns[i].Visibility == Visibility.Visible) ? master.Columns[i].ActualWidth : 0);
                    slave.Columns[i].Visibility = master.Columns[i].Visibility;
                    slave.Columns[i].Width = master.Columns[i].Width;
                    if (master.Columns[i].DisplayIndex < cols) display[master.Columns[i].DisplayIndex] = i;
                }
                for (int i = 0; i < cols; i++)
                {
                    if (display[i] != null) slave.Columns[(int)display[i]].DisplayIndex = i;
                }
            }
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void editColPaid_KeyUp(object sender, KeyEventArgs e)
        {
            //UpdateTotals();
        }

        private void DebtDetailToggleSizeButton_Click(object sender, EventArgs e)
        {
            if (debtDetailDataGrid.MaxHeight < 200)
            {
                debtDetailDataGrid.MaxHeight = 400;
                DebtDetailToggleSizeButton.IsUpsideDown = true;
            }
            else
            {
                debtDetailDataGrid.MaxHeight = 120;
                DebtDetailToggleSizeButton.IsUpsideDown = false;
            }

        }

        /////////////////////////////////////////////////////////////
        // Temporary

        private void ShowDummyDataButton_Click(object sender, EventArgs e)
        {
            if (DummyData == null)
            {
                DummyData = MakeDummyData();
                this.Invoices = DummyData;
            }
            else if (this.Invoices != DummyData)
            {
                this.Invoices = DummyData;
            }
            else
            {
                this.Invoices = (this.Account != null) ? this.Account.AccountInvoices : null;
            }
        }

        ObservableCollection<AccountInvoiceTransport> DummyData;
        private ObservableCollection<AccountInvoiceTransport> MakeDummyData()
        {
            ObservableCollection<AccountInvoiceTransport> Invoices = new ObservableCollection<AccountInvoiceTransport>();
            for (int i = 0; i < 25; i++)
            {
                AccountInvoiceTransport Invoice = new AccountInvoiceTransport();
                Invoice.AccountInvoiceId = i;
                Invoice.Amount = new CurrencyTransport();
                Invoice.Amount.CurrencyCode = "GBP";
                Invoice.Amount.Amount = 10;
                Invoice.AssociatedWithChase = true;
                Invoice.InvoiceDate = new DateTime(2011, 3, 4);
                Invoice.InvoiceNo = "INV2553883/4";
                Invoice.IsInQuery = false;
                Invoice.Status = i % 3;
                Invoices.Add(Invoice);
                //Invoice.Amount.PropertyChanged += new PropertyChangedEventHandler(Amount_PropertyChanged);
                Invoice.PropertyChanged += new PropertyChangedEventHandler(Invoice_PropertyChanged);
            }

            return Invoices;
        }

    }

    public enum DebtAnalysisTabSelection
    {
        Breakdown = 0,
        Expected = 1,
        Invoicing = 2,
        Reason = 3,
    }

    public class DebtSummaryObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged(string propertyName)
        {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null))
            {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }

        public DebtSummaryObject()
        {
            this.Description = "Totals";
 //           this.Paid = new Money2(300);
 //           this.Balance = new Money2(250);
        }

        private String _description;
        public String Description
        {
            get { return _description; }
            set
            {
                if (value != _description)
                {
                    _description = value;
                    RaisePropertyChanged("Description");
                }
            }
        }

        private Money2 _debtPassed;
        public Money2 DebtPassed
        {
            get { return _debtPassed; }
            set
            {
                if (value != _debtPassed)
                {
                    _debtPassed = value;
                    RaisePropertyChanged("DebtPassed");
                }
            }
        }

        private Money2 _lpcda;
        public Money2 Lpcda
        {
            get { return _lpcda; }
            set
            {
                if (value != _lpcda)
                {
                    _lpcda = value;
                    RaisePropertyChanged("Lpcda");
                }
            }
        }

        private Money2 _paid;
        public Money2 Paid
        {
            get { return _paid; }
            set
            {
                if (value != _paid)
                {
                    _paid = value;
                    RaisePropertyChanged("Paid");
                }
            }
        }

        private Money2 _balance;
        public Money2 Balance
        {
            get { return _balance; }
            set
            {
                if (value != _balance)
                {
                    _balance = value;
                    RaisePropertyChanged("Balance");
                }
            }
        }

        private Money2 _paidPreviously;
        public Money2 PaidPreviously
        {
            get { return _paidPreviously; }
            set
            {
                if (value != _paidPreviously)
                {
                    _paidPreviously = value;
                    RaisePropertyChanged("PaidPreviously");
                }
            }
        }

        private Money2 _newBalance;
        public Money2 NewBalance
        {
            get { return _newBalance; }
            set
            {
                if (value != _newBalance)
                {
                    _newBalance = value;
                    RaisePropertyChanged("NewBalance");
                }
            }
        }

        private Money2 _expected;
        public Money2 Expected
        {
            get { return _expected; }
            set
            {
                if (value != _expected)
                {
                    _expected = value;
                    RaisePropertyChanged("Expected");
                }
            }
        }
    }

}
